<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Validate;
use app\facade\Redis;
use app\models\{User as Users, Hall, HallTrade, HallTradeAppeal, Machine, MachineLog, Withdraw, UserAuth, UserConfig, Config, Payment, MoneyLog};


class User extends Base
{

    public function user()
    {
        $model = new Users();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['mobile'])) {
            $list = $list->where('id|mobile', 'like', '%' . $data['mobile'] . '%');
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['pmobile'])) {
            $mobile = (new Users())->where('id|mobile', 'like', '%' . $data['pmobile'] . '%')->column('id') ?? [];
            $list = $list->where(['pid' => $mobile]);
        }
        if (!empty($data['level'])) {
            $list = $list->where('level', $data['level']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $result['recharge'] = (new MoneyLog())->where(['user_id' => $result['id'], 'atype' => 1, 'type' => 1])->sum('money');
            $result['withdraw'] = (new Withdraw())->where(['user_id' => $result['id'], 'cointype' => 1, 'status' => 2])->sum('coinnum');
            $result['pmobile'] =  (new Users())->where('id', $result['pid'])->value('mobile');
            $result['level_text'] = config()['config']['userlevel'][$result['level']];
            return $result;
        });
        $level = config()['config']['userlevel'];
        return view('', ['list' => $list, 'level' => $level]);
    }

    public function User_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['code' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'id' => 'require',
                'mobile' => 'require',
            ], [
                'id.require' => '用户ID不能为空',
                'mobile.require' => '手机号码不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $user = (new Users())->where('id', $data['id'])->find();
            $data = [];
            if (!empty($data['mobile']) && $data['mobile'] != $user['mobile']) {
                $ismobile = (new Users())->where('mobile', $data['mobile'])->find();
                if (!empty($ismobile)) {
                    return json(['status' => 1, 'data' => [], 'msg' => '手机用户已存在']);
                }
            } else {
                unset($data['mobile']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            if (!empty($data['trade'])) {
                $data['trade'] = md5(md5($data['trade']));
            }
            $result = (new Users())->allowfield(true)->save($data, ['id' => $data['id']]);
            if ($result) {
                return json(['status' => 0, 'msg' => '操作成功']);
            } else {
                return json(['status' => 1, 'msg' => '操作失败']);
            }
        } else {
            $id = $this->request->get('id');
            $level = config()['config']['userlevel'];
            $row = (new Users())->where('id', $id)->find();
            return view('', ['row' => $row, 'level' => $level]);
        }
    }

    public function moneylog()
    {
        $ModelFun = new MoneyLog();
        $data = $this->request->get();
        $list = $ModelFun->order('id desc');
        if (!empty($data['mobile'])) {
            $id = (new Users())->where('id|mobile', $data['mobile'])->value('id');
            $list = $list->where('user_id', $id);
        }
        if (!empty($data['pmobile'])) {
            $comeid = (new Users())->where('id|mobile', $data['pmobile'])->value('id');
            $list = $list->where('comeuser_id', $comeid);
        }
        if (!empty($data['type'])) {
            $list = $list->where('type', $data['type']);
        }
        if (!empty($data['atype'])) {
            $list = $list->where('atype', $data['atype']);
        }
        $type = config()['config']['type'];
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($user) {
            $user['mobile'] = (new Users())->where('id', $user['user_id'])->value('mobile');
            $user['type_text'] = config()['config']['type'][$user['type']];
            if ($user['comeuser_id'] > 0) {
                $user['comemobile'] = (new Users())->where('id', $user['comeuser_id'])->value('mobile');
            } else {
                $user['comemobile'] = '';
            }
            return $user;
        });
        return view('', ['list' => $list, 'type' => $type]);
    }

    public function money_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            $validate = new Validate([
                'user_id' => 'require|gt:0',
                'type' => 'require|gt:0',
                'money' => 'require|float',
            ], [
                'user_id.require' => '用户ID不能为空',
                'user_id.gt' => '用户必须大于0',
                'type.require' => '币种类型不能为空',
                'type.gt' => '币种类型必须大于0',
                'money.require' => '修改数目不能为空',
                'money.float' => '修改数目必须是数字或小数',
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            //判断手机号码是否已存在
            $user = (new Users())->where('id', $data['user_id'])->find();
            if (empty($user)) {
                return json(['status' => 1, 'data' => [], 'msg' => '用户不存在']);
            }
            Db::startTrans();
            try {
                (new Users())->MoneyEdit($user, $data['type'], 10, $data['money'], '资产变化', 0, 0, 0);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '修改成功']);
        } else {
            return view();
        }
    }


    public function payment()
    {
        $model = new Payment();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['mobile'])) {
            $mobile = (new Users())->where('id|mobile', 'like', '%' . $data['mobile'] . '%')->column('id') ?? [];
            $list = $list->where(['user_id' => $mobile]);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $result['mobile'] =  (new Users())->where('id', $result['user_id'])->value('mobile');
            return $result;
        });
        return view('', ['list' => $list]);
    }

    public function hall()
    {
        $model = new Hall();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['mobile'])) {
            $mobile = (new Users())->where('id|mobile', 'like', '%' . $data['mobile'] . '%')->column('id') ?? [];
            $list = $list->where(['user_id' => $mobile]);
        }
        if (!empty($data['payment'])) {
            $list = $list->where('payment', 'like', '%' . $data['payment'] . '%');
        }
        if (!empty($data['hall_no'])) {
            $list = $list->where('hall_no', 'like', '%' . $data['hall_no'] . '%');
        }
        if (isset($data['status']) && $data['status'] != "") {
            $list = $list->where('status', $data['status']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $result['status_text'] = config()['config']['hall'][$result['status']] ?? "";
            $result['payment'] = json_decode($result['payment'], true);
            $result['mobile'] = (new Users())->where('id', $result['user_id'])->value('mobile');
            return $result;
        });
        $status = config()['config']['hall'];
        return view('', ['list' => $list, 'status' => $status]);
    }

    public function halltradeappeal()
    {

        $model = new HallTradeAppeal();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['trade_id'])) {
            $hallid = (new HallTrade())->where('id|hall_no', 'like', '%' . $data['trade_id'] . '%')->column('id') ?? [];
            $list = $list->where(['trade_id' =>  $hallid]);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $result['proof'] = json_decode($result['proof'], true) ?? [];
            $result['mobile'] = (new Users())->where('id', $result['user_id'])->value('mobile');
            $result['hall_no'] = (new HallTrade())->where('id', $result['trade_id'])->value('hall_no');
            return $result;
        });
        return view('', ['list' => $list]);
    }

    public function hallcacel()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        $hall = (new Hall())->where(['id' => $data['id']])->find();
        if (!$hall) {
            return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
        }
        if ($hall->status != 0) {
            return json(['status' => 1, 'data' => [], 'msg' => '订单状态不可取消']);
        }
        Db::startTrans();
        try {
            (new Hall())->where('id', $data['id'])
                ->where('status', 0)
                ->update([
                    'status' => 9,
                    'deleted' => date('Y-m-d H:i:s'),
                    'text' => '系统操作'
                ]);
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $exception->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function halltrade()
    {
        $model = new HallTrade();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['bmobile'])) {
            $mobile = (new Users())->where('id|mobile', 'like', '%' . $data['bmobile'] . '%')->column('id') ?? [];
            $list = $list->where(['buyer_id' => $mobile]);
        }
        if (!empty($data['smobile'])) {
            $mobile = (new Users())->where('id|mobile', 'like', '%' . $data['smobile'] . '%')->column('id') ?? [];
            $list = $list->where(['seller_id' => $mobile]);
        }
        if (!empty($data['ordersn'])) {
            $hallid = (new Hall())->where('id|hall_no', 'like', '%' . $data['ordersn'] . '%')->column('id') ?? [];
            $list = $list->where(['hall_id' => $hallid]);
        }
        if (!empty($data['trade_type'])) {
            $list = $list->where('payment', 'like', '%' . $data['payment'] . '%');
        }
        if (!empty($data['hall_no'])) {
            $list = $list->where('hall_no', 'like', '%' . $data['hall_no'] . '%');
        }
        if (isset($data['status']) && $data['status'] != "") {
            $list = $list->where('status', $data['status']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $result['status_text'] = config()['config']['halltrade'][$result['status']] ?? "";
            $result['bmobile'] = (new Users())->where('id', $result['buyer_id'])->value('mobile');
            $result['smobile'] = (new Users())->where('id', $result['seller_id'])->value('mobile');
            $result['ordersn'] = (new Hall())->where('id', $result['hall_id'])->value('hall_no');
            return $result;
        });
        $status = config()['config']['halltrade'];
        return view('', ['list' => $list, 'status' => $status]);
    }

    public function halltradestr()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        if (empty($data['id']) || empty($data['status'])) {
            return json(['status' => 1, 'data' => [], 'msg' => '参数错误']);
        }
        //查找交易订单
        $trade = (new halltrade())->where('id', $data['id'])->find();
        if (empty($trade)) {
            return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
        }
        if ($trade['status'] != 0 && $trade['status'] != 1) {
            return json(['status' => 1, 'data' => [], 'msg' => '交易订单不可操作']);
        }
        Db::startTrans();
        try {
            if ($data['status'] == 2) {
                $buyuser = (new Users())->where('id', $trade['buyer_id'])->find();
                (new HallTrade())->where('id', $trade['id'])
                    ->where('status', 1)
                    ->update([
                        'status' => $data['status'],
                        'finishtime' => date('Y-m-d H:i:s')
                    ]);
                (new Users())->MoneyEdit($buyuser, 3, 6, $trade['num'], '交易购买', $trade['id'], 0, 0);
            }
            if ($data['status'] == 10) {
                $selluser = (new Users())->where('id', $trade['seller_id'])->find();
                (new HallTrade())->where('id', $trade['id'])->update(['status' => $data['status'], 'caceltime' => date('Y-m-d H:i:s')]);
                (new Users())->MoneyEdit($selluser, 3, 7, ($trade['num'] + $trade['handfee']), '交易售卖' . $trade['num'] . '取消', $trade['id'], $trade['handfee'], 0);
            }
            // $this->checkHall($trade->hall_id);
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $exception->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function halltradeappealstr()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        if (empty($data['id']) || empty($data['status'])) {
            return json(['status' => 1, 'data' => [], 'msg' => '参数错误']);
        }
        $tradeappeal = (new HallTradeAppeal())->where('id', $data['id'])->find();
        if (empty($tradeappeal) ||  $tradeappeal['status'] != 1) {
            return json(['status' => 1, 'data' => [], 'msg' => '订单状态不可审核']);
        }
        //查找交易订单
        $trade = (new HallTrade())->where('id', $tradeappeal['trade_id'])->find();
        if (empty($trade)) {
            return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
        }
        if ($trade['status'] != 8 && $trade['status'] != 9) {
            return json(['status' => 1, 'data' => [], 'msg' => '交易订单不是申诉状态']);
        }
        Db::startTrans();
        try {
            (new HallTradeAppeal())->where('id', $data['id'])->update(['status' => 2]);
            if ($data['status'] == 2) {
                $buyuser = (new Users())->where('id', $trade['buyer_id'])->find();
                (new HallTrade())->where('id', $trade['id'])
                    ->where('status', 1)
                    ->update([
                        'status' => 2,
                        'finishtime' => date('Y-m-d H:i:s')
                    ]);
                (new Users())->MoneyEdit($buyuser, 3, 6, $trade['num'], '交易购买', $trade['id'], 0, 0);
            }
            if ($data['status'] == 10) {
                $selluser = (new Users())->where('id', $trade['seller_id'])->find();
                (new HallTrade())->where('id', $trade['id'])->update(['status' => 10]);
                (new Users())->MoneyEdit($selluser, 3, 7, ($trade['num'] + $trade['handfee']), '交易售卖' . $trade['num'] . '取消', $trade['id'], $trade['handfee'], 0);
            }
            // $this->checkHall($trade->hall_id);
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $exception->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    // protected function checkHall($id)
    // {
    //     $hall = (new Hall())->where('id', $id)->find();
    //     $results = (new HallTrade())
    //         ->where('hall_id', $id)
    //         ->where('status', 'in', '0,1,8,9')
    //         ->field('id')
    //         ->select();
    //     if (count($results) > 0 && $hall['status'] == 1 && $hall['surplus'] > 0) {
    //         if ($hall['type'] == 2) {
    //             (new Hall())->where('id', $id)->update([
    //                 'status' => 9,
    //                 'deleted' => date('Y-m-d H:i:s'),
    //             ]);
    //         } else {
    //             (new Hall())->where('id', $id)->update(['status' => 0]);
    //         }
    //     }
    //     if (count($results) <= 0 && $hall['surplus'] == 0) {
    //         (new Hall())->where('id', $id)->update(['status' => 2]);
    //     }
    //     return true;
    // }

    public function machine()
    {
        $model = new Machine();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['level'])) {
            $list = $list->where('level', $data['level']);
        }
        if (!empty($data['name'])) {
            $list = $list->where('name', 'like', '%' . $data['name'] . '%');
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $status = [
                1 => '上架',
                2 => '下架'
            ];
            $result['level_text'] = config()['config']['machinelevel'][$result['level']] ?? "";
            $result['status_text'] = $status[$result['status']] ?? "";

            return $result;
        });
        $level = config()['config']['machinelevel'];
        return view('', ['list' => $list, 'level' => $level]);
    }

    public function machine_edit()
    {
        if ($this->request->isPost()) {
            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = input('post.');
            if (empty($data['id'])) {
                unset($data['file']);
                $data['id'] = (new Machine())->allowField(true)->insertGetID($data);
                if ($data['id']) {
                    Redis::set('machine_' . $data['id'], $data['sku'] ?? 0);
                    $result = true;
                }
            } else {
                $result = (new Machine())->allowField(true)->save($data, ['id' => $data['id']]);
            }
            if ($result) {
                return json(['status' => 0, 'msg' => '操作成功']);
            } else {
                return json(['status' => 1, 'msg' => '操作失败']);
            }
        } else {
            $id = $this->request->get('id');
            $row = (new Machine())->where('id', $id)->find();
            $level = config()['config']['machinelevel'];

            return view('', ['row' => $row, 'level' => $level]);
        }
    }


    public function machinelog()
    {
        $model = new MachineLog();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        if (!empty($data['level'])) {
            $list = $list->where('level', $data['level']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $status = [
                1 => '购买',
                2 => '赠送'
            ];
            $status = [
                1 => '进行中',
                2 => '完成'
            ];
            $result['level_text'] = config()['config']['machinelevel'][$result['level']] ?? "";
            $result['status_text'] = $status[$result['status']] ?? "";

            return $result;
        });
        $level = config()['config']['machinelevel'];
        return view('', ['list' => $list, 'level' => $level]);
    }

    public function withdraw()
    {
        $model = new Withdraw();
        $data = $this->request->get();
        $list = $model->order('id desc');
        if (!empty($data['mobile'])) {
            $mobile = (new Users())->where('id|mobile', 'like', '%' . $data['mobile'] . '%')->column('id') ?? [];
            $list = $list->where(['user_id' => $mobile]);
        }
        if (!empty($data['address'])) {
            $list = $list->where('address', 'like', '%' . $data['address'] . '%');
        }
        if (isset($data['status']) && $data['status'] != "") {
            $list = $list->where('status', $data['status']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $result['status_text'] = config()['config']['withdrawstatus'][$result['status']] ?? "";
            $result['coin_text'] = config()['config']['withdrawtype'][$result['cointype']] ?? "";
            $result['mobile'] = (new Users())->where('id', $result['user_id'])->value('mobile');
            return $result;
        });
        $status = config()['config']['withdrawstatus'];
        return view('', ['list' => $list, 'status' => $status]);
    }

    public function withdrawstr()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        if (empty($data['id']) || empty($data['status'])) {
            return json(['status' => 1, 'data' => [], 'msg' => '参数错误']);
        }
        //查找交易订单
        $withdraw = (new Withdraw())->where('id', $data['id'])->find();
        if (empty($withdraw)) {
            return json(['status' => 1, 'data' => [], 'msg' => '订单不存在']);
        }
        if ($withdraw['status'] != 1) {
            return json(['status' => 1, 'data' => [], 'msg' => '订单不可操作']);
        }
        $user = (new Users())->where('id', $withdraw['user_id'])->find();
        Db::startTrans();
        try {
            (new Withdraw())->where('id', $withdraw['id'])
                ->where('status', 1)
                ->update([
                    'status' => $data['status']
                ]);
            if ($data['status'] == 3 && $withdraw['cointype'] == 1) {
                (new Users())->MoneyEdit($user, 1, 8, ($withdraw['coinnum']), '提现申请驳回', $withdraw['id'], $withdraw['handfee'], 0);
            }
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $exception->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function userauth()
    {
        $model = new UserAuth();
        $data = $this->request->get();
        $list = $model->order('user_id desc');
        if (!empty($data['mobile'])) {
            $mobile = (new Users())->where('id|mobile', 'like', '%' . $data['mobile'] . '%')->column('id') ?? [];
            $list = $list->where(['user_id' => $mobile]);
        }
        if (!empty($data['address'])) {
            $list = $list->where('name|cards', 'like', '%' . $data['address'] . '%');
        }
        if (!empty($data['status'])) {
            $list = $list->where('status', $data['status']);
        }
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $status = [
                1 => '待审核',
                2 => '审核通过',
                3 => '审核驳回'
            ];
            $result['status_text'] = $status[$result['status']] ?? "";
            $result['mobile'] = (new Users())->where('id', $result['user_id'])->value('mobile');
            return $result;
        });
        return view('', ['list' => $list, 'status' => [
            1 => '待审核',
            2 => '审核通过',
            3 => '审核驳回'
        ]]);
    }
    public function userauthstr()
    {
        $rdslist = Redis::get('clickreturn');
        if ($rdslist) {
            return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
        }
        Redis::setex('clickreturn', 2, 1);
        $data = $this->request->post();
        if (empty($data['id']) || empty($data['status'])) {
            return json(['status' => 1, 'data' => [], 'msg' => '参数错误']);
        }
        //查找交易订单
        $userauth = (new UserAuth())->where('user_id', $data['id'])->find();
        if (empty($userauth)) {
            return json(['status' => 1, 'data' => [], 'msg' => '信息不存在']);
        }
        if ($userauth['status'] != 1) {
            return json(['status' => 1, 'data' => [], 'msg' => '信息不可操作']);
        }
        $user = (new Users())->where('id', $userauth['user_id'])->find();
        $givepmoney = (float)(new Config())->where('key_value', 'givepmoney')->value('value') ?? 0;
        Db::startTrans();
        try {
            (new UserAuth())->where('user_id', $userauth['user_id'])
                ->where('status', 1)
                ->update([
                    'status' => $data['status']
                ]);
            //审核通过操作
            if ($data['status'] == 2) {
                (new Users())->where('id', $userauth['user_id'])->update(['auth' => 2, 'level' => 1]);
                (new Users())->MoneyEdit($user, 2, 9, $givepmoney, '实名认证赠送', 0, 0, 0);
                (new Users())->MoneyEdit($user, 3, 0, 0, '审核实名升级判断', 0, 0, 0);
                if ($user['pid'] > 0) {
                    $puser = (new Users())->where('id', $user['pid'])->find();
                    $pgivepmoney = (float)(new Config())->where('key_value', 'pgivepmoney')->value('value') ?? 0;
                    (new Users())->MoneyEdit($puser, 2, 12, $pgivepmoney, '推荐赠送', 0, 0, $user['id']);
                }
            }
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            return json(['status' => 1, 'data' => [], 'msg' => $exception->getMessage()]);
        }
        return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
    }

    public function userconfig()
    {
        $model = new UserConfig();
        $data = $this->request->get();
        $list = $model->order('level desc');
        $status = config()['config']['userlevel'] ?? [];
        $list = $list->paginate(15, false, ['query' => $this->request->param()])->each(function ($result) {
            $result['level_text'] = config()['config']['userlevel'][$result['level']] ?? "";
            return $result;
        });
        return view('', ['list' => $list, 'status' => $status]);
    }

    public function userconfig_edit()
    {
        if ($this->request->isPost()) {

            $rdslist = Redis::get('clickreturn');
            if ($rdslist) {
                return json(['status' => 1, 'data' => [], 'msg' => '请' . $rdslist . 's后再试']);
            }
            Redis::setex('clickreturn', 2, 1);
            $data = $this->request->post();
            if (empty($data['id'])) {
                return json(['status' => 1, 'data' => [], 'msg' => '参数错误']);
            }
            //查找交易订单
            $userconfig = (new UserConfig())->where('id', $data['id'])->find();
            if (empty($userconfig)) {
                return json(['status' => 1, 'data' => [], 'msg' => '信息不存在']);
            }
            $userconfig = (new UserConfig())->where('level', $data['level'])->find();
            if (!empty($userconfig) && $userconfig['id'] != $data['id']) {
                return json(['status' => 1, 'data' => [], 'msg' => '等级已存在']);
            }
            Db::startTrans();
            try {
                (new UserConfig())->allowField(true)->save($data, ['id' => $data['id']]);
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                return json(['status' => 1, 'data' => [], 'msg' => $exception->getMessage()]);
            }
            return json(['status' => 0, 'data' => [], 'msg' => '操作成功']);
        } else {
            $id = $this->request->get('id');
            $row = (new UserConfig())->where('id', $id)->find();
            $level = config()['config']['userlevel'] ?? [];
            return view('', ['row' => $row, 'level' => $level]);
        }
    }

    //用户层级关系
    public function tree()
    {
        return view('user/tree', [
            'count' => Users::count(),
        ]);
    }

    public function tree_data()
    {
        $data = $this->request->get();
        if (isset($data['mobile']) && !isset($data['id'])) {
            $results = (new Users())->where('mobile', $data['mobile'])->select();
        } else {
            $data['id'] = $data['id'] ?? 0;
            $results = (new Users())->where('pid', $data['id'])->select();
        }
        $arr = [];
        foreach ($results as $k => $result) {
            $user_id = (new Users())->where('find_in_set(' . $result['id'] . ',pstree)')->column('id') ?? [];
            $arr[$k]['id'] = $result['id'];
            $arr[$k]['name'] = $result['mobile'];
            $arr[$k]['ttotal'] = (new Users())->where(['id' => $user_id])->sum('tmoney');
            $arr[$k]['ptotal'] = (new Users())->where(['id' => $user_id])->sum('pmoney');
            $arr[$k]['utotal'] = (new Users())->where(['id' => $user_id])->sum('umoney');
            $arr[$k]['recharge'] = (new MoneyLog())->where(['user_id' => $user_id, 'atype' => 1, 'type' => 1])->sum('money');
            $arr[$k]['withdraw'] = (new Withdraw())->where(['user_id' => $user_id, 'cointype' => 1, 'status' => 2])->sum('coinnum');
            $arr[$k]['isParent'] = 'true';
        }
        return json($arr);
    }
}
